"""
Data models for LogRun Manager.
"""

import json
from dataclasses import dataclass, asdict
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Any


@dataclass
class LogEntry:
    """Represents a single log entry."""
    
    id: int
    command: str
    log_file: str
    start_time: datetime
    end_time: Optional[datetime]
    exit_code: Optional[int]
    duration: Optional[float]  # in seconds
    tags: List[str]
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for JSON serialization."""
        return {
            'id': self.id,
            'command': self.command,
            'log_file': self.log_file,
            'start_time': self.start_time.isoformat() if self.start_time else None,
            'end_time': self.end_time.isoformat() if self.end_time else None,
            'exit_code': self.exit_code,
            'duration': self.duration,
            'tags': self.tags
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'LogEntry':
        """Create LogEntry from dictionary."""
        return cls(
            id=data['id'],
            command=data['command'],
            log_file=data['log_file'],
            start_time=datetime.fromisoformat(data['start_time']) if data['start_time'] else None,
            end_time=datetime.fromisoformat(data['end_time']) if data['end_time'] else None,
            exit_code=data.get('exit_code'),
            duration=data.get('duration'),
            tags=data.get('tags', [])
        )
    
    @property
    def status(self) -> str:
        """Get the status of the log entry."""
        if self.end_time is None:
            return "running"
        elif self.exit_code == 0:
            return "success"
        else:
            return "failed"
    
    @property
    def command_name(self) -> str:
        """Extract the main command name."""
        return self.command.split()[0] if self.command else ""
    
    @property
    def subcommand(self) -> str:
        """Extract the subcommand if available."""
        parts = self.command.split()
        return parts[1] if len(parts) > 1 else ""


@dataclass
class LogRunConfig:
    """Configuration for LogRun Manager."""
    
    log_directory: str = "logs"
    max_history: int = 1000
    cleanup_days: int = 30
    default_tags: List[str] = None
    
    def __post_init__(self):
        if self.default_tags is None:
            self.default_tags = []